/*
 *     This file is part of Mobile GPS Logger.
 *
 *     Mobile GPS Logger is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Mobile GPS Logger is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License v3 for more details.
 *
 *     You should have received a copy of the GNU General Public License v3
 *     along with Mobile GPS Logger. If not, see <http://www.gnu.org/licenses/>.
 */

package cx.ath.skyflyer.contactless;

import javax.microedition.contactless.ContactlessException;
import javax.microedition.contactless.DiscoveryManager;
import javax.microedition.contactless.TargetListener;
import javax.microedition.contactless.TargetProperties;
import javax.microedition.contactless.TargetType;
import javax.microedition.contactless.ndef.NDEFMessage;
import javax.microedition.contactless.ndef.NDEFRecord;
import javax.microedition.contactless.ndef.NDEFRecordType;
import javax.microedition.contactless.ndef.NDEFTagConnection;
import javax.microedition.io.Connector;

/**
 *
 * @author Ahti Legonkov
 */
public class Sharer {

    public static Object registerDataSource(final DataSource ds) throws GpsContactlessException {
        try {
            DiscoveryManager dm = DiscoveryManager.getInstance();
            TargetListener targetListener = new TargetListener() {

                public void targetDetected(TargetProperties[] prop) {
                    // if there is no information available on the tags
                    // found, exit Method.
                    if (prop.length == 0) {
                        return;
                    }

                    // Create a new NDEF Connection in order
                    // to write an NDEF EXT to the tag.
                    NDEFTagConnection ndconn = null;
                    try {
                        // create an ndef tag connection.
                        String ur = prop[0].getUrl(Class.forName("javax.microedition.contactless.ndef.NDEFTagConnection"));

                        // open the NDEF Connection
                        ndconn = (NDEFTagConnection) Connector.open(ur);

                        // now create the NDEFRecord
                        NDEFRecordType myType = new NDEFRecordType(NDEFRecordType.EXTERNAL_RTD, "urn:nfc:ext:skyflyer.ath.cx:gpslog");

                        // create Data-Container for Tag
                        NDEFRecord myRec = new NDEFRecord(myType, null, ds.getData().getBytes());

                        NDEFRecord[] myRecArray = new NDEFRecord[]{myRec};
                        NDEFMessage myMessage = new NDEFMessage(myRecArray);

                        // write Information to Tag
                        ndconn.writeNDEF(myMessage);

                        //m_Alert.display("Writing successful!", AlertType.INFO);
                    } catch (Exception e) {
                        //m_Alert.display("Error Writing to Tag! " + e.toString(), AlertType.ERROR);
                        ds.reportError("Error writing to tag", e);
                    }
                    finally {
                        DiscoveryManager dm = DiscoveryManager.getInstance();
                        dm.removeTargetListener(this, TargetType.RFID_TAG);
                    }
                    try {
                        ndconn.close();
                    } catch (Exception e) {
                        // just swallow it.
                    }
                }
            };

            dm.addTargetListener(targetListener, TargetType.RFID_TAG);

            return targetListener;

        } catch (ContactlessException ce) {
            //m_Alert.display("Unable to Register Targetlistener:" + ce.toString(), AlertType.ERROR);
            //Display.getDisplay(m_Midlet).setCurrent(m_Form);
            //return;
            throw new GpsContactlessException("Unable to register TargetListener", ce.getMessage());
        }
    }

    public static void unregisterDataSource(Object o) {
        DiscoveryManager dm = DiscoveryManager.getInstance();
        TargetListener targetListener = (TargetListener)o;
        dm.removeTargetListener(targetListener, TargetType.RFID_TAG);
    }
}
